﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

/*
 * 对TcpListener、TcpClient、UdpClient做了一些简单应用
 */

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {

        }

        static void TCPServerSample() {
            TcpListener listener = new TcpListener(new IPAddress(0), 2000);  // 本地端口
            listener.Start();

            TcpClient client = listener.AcceptTcpClient();  // 接受连接
            byte[] buffer = new byte[client.ReceiveBufferSize];
            NetworkStream stream = client.GetStream();
            int len = stream.Read(buffer, 0, buffer.Length);
            stream.Write(buffer, 0, len);
            stream.Close();
            client.Close();

            listener.Stop();
        }

        static void TCPClientSample() {
            TcpClient client = new TcpClient(new IPEndPoint(0, 0));  // 本地端口
            client.Connect("192.168.1.111", 1000);  // 远端
            NetworkStream stream = client.GetStream();

            byte[] bt = Encoding.UTF8.GetBytes("Sample Text");
            stream.Write(bt, 0, bt.Length);

            byte[] bt2 = new byte[1000];
            stream.Read(bt2, 0, 1000);

            stream.Close();
            client.Close();
        }

        static void UDPSample() {
            UdpClient uc = new UdpClient(0);  // 本地端口
            uc.Connect("192.168.1.111", 17224);  // 远端
            byte[] bt = Encoding.UTF8.GetBytes("Sample Text");
            uc.Send(bt, bt.Length);

            IPEndPoint ip = new IPEndPoint(0, 0);
            byte[] bt2 = uc.Receive(ref ip);

            uc.Close();
        }
    }
}
